/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
/*
树的层次遍历抓住三个关键点：front rear levelLoc(每层结束的位置)
*/
var largestValues = function(root) {
    if(root == null) return []
    let q = [], ans = []
    let front = 0, rear = 1
    let levelLoc = 1 // 每层结束的位置
    q.push(root)
    let max = root.val
    while(front < rear) {
        let node = q[++front]
        if(node.val > max) max = node.val
        if(node.left) q[++rear] = node.left
        if(node.right) q[++rear] = node.right
        if(front == levelLoc) {
            levelLoc = rear
            ans.push(max)
            max = q[front+1].val
        }

    }
    return ans
};